<template>
  <view>
    <u-sticky>
      <u-navbar back-text=" " title="签证洽商单" :background="background" title-color="#ffffff" :custom-back="customBack" back-icon-color="#ffffff" ref="navbar" title-size="36"></u-navbar>
      <xmInfo
        :projectno="itemContent.projectno"
        :projectname="itemContent.projectname"
        ref="xmInfo"
        class="u-sticky"
      ></xmInfo>
    </u-sticky>
    <scroll-view
      scroll-y="true"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :scrolltolower-enabled="true"
      :refresher-triggered="triggered"
      @refresherrefresh="refresherrefresh"
      @scrolltoupper="refresherrefresh"
      class="scroll-view-class"
      :style="{ height: computedScrollViewHeight }"
    >
    <view
        class="scroll-content"
        ref="scrollContent"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        :style="{ height: computedScrollViewHeight  }"
      >
        <view v-for="(item,index) in list" class="cu-item shadow"  :key="item.id">
          <view
            class="cu-form-group  justify-start"
          >
            <view  class="title">
              <view
                style="
                  display: inline-block;
                  padding: 5px;
                  background: #3e97b0;
                  color: #fff;
                  width: 40px;
                  text-align: center;
                  font-style: italic;
                  font-weight: bold;
                "
              >
                {{ index + 1 }}
              </view>
            </view>
            <view class="flex align-center justify-between  flex-sub">
              <view class="text-xl text-bold">{{ item.djno ? item.djno : "" }}</view>
              <view><dictLabel
              :value="item.status ? item.status : 0"
              dict-type="bpm_biz_status"
              :dict-list="dictList"
              :fontSize="'30rpx'"
            ></dictLabel></view>
            </view>
          </view>


          <!-- <view class="cu-form-group">
            <view class="text-xl text-bold">洽商单编号</view>
            <view class="text-xl text-bold">{{ item.djno ? item.djno : "" }}</view>
          </view> -->
          <view class="cu-form-group justify-start">
            <view class="title">变更类型</view>
            <!-- <js-select v-model="item.designchangereasonid" dict-type="zf_designChg_reson_type"
						placeholder="请选择分类"></js-select> -->
            <view> <js-select v-model="item.designchangereasonid" dict-type="zf_designChg_reson_type" disabled style="text-align: right;"></js-select> </view>
          </view>
          <view class="cu-form-group justify-start">
            <view class="title">变更原因</view>
            <view>{{ item.remarks || " " }}</view>
          </view>
          <view class="cu-form-group justify-start">
            <view class="title">创建时间</view>
            <view>{{ item.createDate || " " }}</view>
          </view>
          <view class="cu-form-group justify-start">
            <view class="title">驳回原因</view>
            <view> {{ item.backResult || " " }}</view>
          </view>
          <view class="cu-form-group justify-start">
            <view class="title">驳回信息</view>
            <view> {{ item.backResultDate || " " }} {{ item.backResultPerson ? '(' + item.backResultPerson + ')' :''}}</view>
          </view>
          <view class="cu-form-group justify-start">
            <view class="title">审核结果</view>
            <view> {{ item.checkResult || ' ' }}</view>
          </view>
          <view class="cu-form-group justify-start">
            <view class="title">接口错误返回信息</view>
            <view> {{ item.errorContent || ""  }}</view>
          </view>
          <view class="cu-form-group justify-start">
            <view class="title">执行状态</view>
            <view> {{ item.isReject || "" }}</view>
          </view>
          <view class="cu-form-group" style="color:#3E97B0 ;"  @click="add(item)">
            <view class="content-footer-right">查看详情</view>
            <u-icon name="arrow-right"></u-icon>
          </view>   
        </view>
        <view v-if="list.length" class="loadmore" style="justify-self: flex-end">
              <u-loadmore :status="loadStatus"></u-loadmore>
            </view>
            <u-empty v-if="!list.length" style="height: 100%;"></u-empty>
      </view>
    </scroll-view>
    <view style="height: 80px" v-if="flag"></view>
    <view class="btn-group cu-bar foot" style="height: 80px" v-if="flag">
      <button class="cu-btn bg-green shadow-blur" @tap="add({designchangereasonid:'0b4c12e9-2971-434a-99aa-e34e4985616a'})">
        <text class="cuIcon-add"></text> 发起签证洽商单
      </button>
    </view>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import dictLabel from "@/pages/zfgs/index/componetns/dictLabel.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo , dictLabel},
  data() {
    return {
      background:{
        backgroundColor: '#3E97B0',
      },
      list: [],
      itemContent: {},
      query: {
        pageNo: 1,
        pageSize: 20,
        // orderBy: "a.create_date desc",
      },
      loadStatus: "loadmore",
      triggered: false,
      dictList: [],
      flag:hasPermission('app:btn:edit:qiashang') ,
      scrollViewHeight: 0,
      headerHeight: 0,
    };
  },
  onShow() {
    this.query.pageNo = 1;
    this.loadData();
  },
  onLoad(e) {
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        this.query.projectno = this.itemContent.projectno;
        this.query.projectname = this.itemContent.projectname;
        this.query.designchangereasonid = '0b4c12e9-2971-434a-99aa-e34e4985616a'

        // this.loadData();
        this.getDictList();
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
  },
  mounted() {
    this.$refs.xmInfo.$on('child-mounted-done', () => {
      this.calculateScrollViewHeight();
    });
  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
    },
  },
  methods: {
    customBack(){
      // 跳转到工作台页面
      // uni.navigateTo({
      //   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
      // });
	  uni.navigateBack({
	    delta: 1,
	  });
    },
    async calculateScrollViewHeight() {
      try {
    // 等待头部高度计算完成
          await new Promise((resolve) => {
            this.$nextTick(() => {
              this.headerHeight = this.$refs.xmInfo.$refs['u-sticky'].height + this.$refs.xmInfo.$refs['u-sticky'].h5NavHeight + this.$refs.navbar.navbarHeight;
              resolve();
            });
          });
          // 计算tabBar高度
          this.tabBarHeight = 90; // 假设tabbar高度为50px，实际应根据实际情况获取

          // 获取屏幕高度
          const systemInfo = uni.getSystemInfoSync();
          const screenHeight = systemInfo.windowHeight;
          console.log('screenHeight',this.headerHeight,this.$refs.xmInfo.$refs['u-sticky']);
          // 计算scroll-view高度
          this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
      } catch (error) {
        console.error('Error while calculating ScrollView height:', error);
      }
    },    
    getDictList() {
      this.$u.api
        .dictListData({ dictType: "bpm_biz_status" })
        .then((res) => {
          this.dictList = res;
        });
    },
    loadMore() {
      this.loadStatus = "loading";
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadData("add");
      }, 100);
    },
    loadData(type) {
      // 循环10次重复赋值
      this.$u.api.zfgs.designNegotiPmNegotiationListData(this.query).then((res) => {
        if (res.list.length >= 0) {
          // this.xmList = res.list
          if (res.list.length < 20 || res.list.length == 0) {
            this.loadStatus = "nomore";
          }
          var data = res.list;
          //模拟收藏

          if (type == "add") {
            for (var i = 0; i < data.length; i++) {
              this.list.push(data[i]);
            }
          } else {
            this.list = data;
          }
        }
      });
    },
    async refresherrefresh() {
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadData();
      setTimeout(() => {
        this.triggered = false;
      }, 500);
      // this.triggered = false;
    },

    add(item) {
      if(item.designchangereasonid == '0b4c12e9-2971-434a-99aa-e34e4985616a'){
        if (item.id) {
            uni.navigateTo({
                url: '/pages/zfgs/design/visanegoti/form?id='+item.id
            })
        } else {
          const xm = {
            projectno: this.itemContent.projectno,
            projectname: this.itemContent.projectname,
            designchangereasonid:item.designchangereasonid
          };
          uni.navigateTo({
            url: "/pages/zfgs/design/visanegoti/form?xm=" + JSON.stringify(xm),
          });
        }
        
      }
    },
  },
  beforeDestroy() {
    // 清理事件监听器
    try {
       this.$refs.xmInfo.$off('child-mounted-done');
     } catch (e) {
       console.log('Error while unbinding event:', e);
     }
  }  
};
</script>
<style lang="scss" scoped>
.cu-bar {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
  position: relative;
}


.dictLabel{
    position: absolute;
    top: 0;
    right: 0;
}
.title {
  width: 280rpx;
}
::v-deep .uni-input-input{
  text-align: right !important;
}
</style>